#include "jsonitem.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QMessageBox>
#include <QJsonParseError>
#include <QJsonDocument>
#include <QJsonObject>

#include "nlohmann/json/json.hpp"

JsonItem::JsonItem(QWidget *parent):
    QWidget(parent)
{
    onInit();
}

void JsonItem::onInit()
{
    QVBoxLayout *mainLayout = new QVBoxLayout();
    this->setLayout(mainLayout);

    m_textEdit = new QTextEdit(this);
    // m_textEdit->setFontFamily("consolas");
    QFont font = QFont("Consolas", 14);
    m_textEdit->setFont(font);
    mainLayout->addWidget(m_textEdit);

    QWidget *underItem = new QWidget(this);
    m_formatBtn = new QPushButton("格式化", underItem);
    m_compressBtn = new QPushButton("压缩", underItem);
    m_escapeBtn = new QPushButton("转义", underItem);
    m_reverseBtn = new QPushButton("去转义", underItem);

    QHBoxLayout *underLayout = new QHBoxLayout();
    underItem->setLayout(underLayout);

    underLayout->addWidget(m_formatBtn);
    underLayout->addWidget(m_compressBtn);
    underLayout->addWidget(m_escapeBtn);
    underLayout->addWidget(m_reverseBtn);

    mainLayout->addWidget(underItem);


    // 信号槽
    connect(m_formatBtn, &QPushButton::clicked, this, &JsonItem::onFormat);
    connect(m_compressBtn, &QPushButton::clicked, this, &JsonItem::onCompress);
    connect(m_escapeBtn, &QPushButton::clicked, this, &JsonItem::onEscape);
    connect(m_reverseBtn, &QPushButton::clicked, this, &JsonItem::onReverse);
}

void JsonItem::onFormat()
{
    QString text = m_textEdit->toPlainText();
    if (text.isEmpty()) {
        return;
    }

    // QJsonParseError err;
    // QJsonDocument doc = QJsonDocument::fromJson(text.toUtf8(), &err);
    // if (err.error != QJsonParseError::NoError) {

    //     return;
    // }

    // const QByteArray &formatArr = doc.toJson(QJsonDocument::Indented);
    //m_textEdit->setText(QString(formatArr));

    try {
        // 使用 nlohmann/json 解析和格式化
        auto j = nlohmann::ordered_json::parse(text.toStdString());
        QString formattedText = QString::fromStdString(j.dump(4));
        m_textEdit->setPlainText(formattedText);
    } catch (const std::exception &e) {
        // 处理解析错误
        //qDebug() << "JSON Error:" << e.what();
        QMessageBox::critical(nullptr, "错误", QString("Json解析失败:%1").arg(e.what()));
        return;
    }
}

void JsonItem::onCompress()
{
    QString text = m_textEdit->toPlainText();
    if (text.isEmpty()) {
        return;
    }

    // QJsonParseError err;
    // QJsonDocument doc = QJsonDocument::fromJson(text.toUtf8(), &err);
    // if (err.error != QJsonParseError::NoError) {

    //     return;
    // }

    // const QByteArray &formatArr = doc.toJson(QJsonDocument::Compact);

    // m_textEdit->setText(QString(formatArr));

    try {
        // 使用 nlohmann/json 解析和格式化
        auto j = nlohmann::ordered_json::parse(text.toStdString());
        QString formattedText = QString::fromStdString(j.dump());
        m_textEdit->setPlainText(formattedText);
    } catch (const std::exception &e) {
        // 处理解析错误
        //qDebug() << "JSON Error:" << e.what();
        QMessageBox::critical(nullptr, "错误", QString("Json解析失败:%1").arg(e.what()));
        return;
    }
}

void JsonItem::onEscape()
{
    QString text = m_textEdit->toPlainText();
    if (text.isEmpty()) {
        return;
    }

    QJsonParseError err;
    QJsonDocument srcDoc = QJsonDocument::fromJson(text.toUtf8(), &err);
    if (err.error != QJsonParseError::NoError) {
        QMessageBox::critical(nullptr, "错误", "Json解析失败:" + err.errorString());
        return;
    }
    // if (srcDoc.isEmpty())
    //     return;

    // 创建临时JSON对象包装输入字符串
    QJsonObject wrapper;
    wrapper["data"] = text;

    // 生成紧凑型JSON字符串
    QJsonDocument doc(wrapper);
    QString jsonStr = doc.toJson(QJsonDocument::Compact);

    // 提取转义后的内容（跳过{"data":" 和最后的"}）
    const int prefixLen = 9;  // {"data":"
    const int suffixLen = 2;  // "}

    m_textEdit->setText(jsonStr.mid(prefixLen, jsonStr.length() - prefixLen - suffixLen));
}

void JsonItem::onReverse()
{
    QString text = m_textEdit->toPlainText();
    if (text.isEmpty()) {
        return;
    }

    QString wrappedJson = QString("{\"data\":\"%1\"}").arg(text);
    // 解析JSON文档
    QJsonParseError parseError;
    QJsonDocument doc = QJsonDocument::fromJson(wrappedJson.toUtf8(), &parseError);

    if(parseError.error != QJsonParseError::NoError && !doc.isObject()) {
        QMessageBox::critical(nullptr, "错误", "Json解析失败:" + parseError.errorString());
        return;
    }

    QJsonObject obj = doc.object();
    if(obj.contains("data") && obj["data"].isString()) {
        text = obj["data"].toString();
        m_textEdit->setText(text);
    }
}
